# 第一阶段：构建前端
FROM node:18-alpine AS frontend-builder
WORKDIR /app/frontend
# 首先复制 package.json，利用缓存层
COPY frontend/package*.json ./
RUN npm config set registry https://registry.npmmirror.com && \
    npm install
COPY frontend .
RUN npm run build

# 第二阶段：构建后端
FROM node:18-alpine AS backend-builder
WORKDIR /app/backend
COPY backend/package*.json ./
RUN npm config set registry https://registry.npmmirror.com && \
    npm install --production
COPY backend .

# 第三阶段：生产环境
FROM node:18-alpine
WORKDIR /app

# 创建非 root 用户
RUN addgroup -S appgroup && adduser -S appuser -G appgroup

# 复制前端构建结果
COPY --from=frontend-builder /app/frontend/dist ./frontend/dist

# 复制后端文件和依赖
COPY --from=backend-builder /app/backend ./backend

# 创建上传目录并设置权限
RUN mkdir -p backend/uploads && \
    chown -R appuser:appgroup /app

# 切换到非 root 用户
USER appuser

# 设置环境变量
ENV NODE_ENV=production \
    PORT=3800 \
    TZ=Asia/Shanghai

# 健康检查
HEALTHCHECK --interval=30s --timeout=3s \
  CMD wget --no-verbose --tries=1 --spider http://localhost:3800/api/health || exit 1

# 暴露端口
EXPOSE 3800

# 启动命令
CMD ["node", "backend/app.js"] 